/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "test_helper.h"
#include "plugins/ecmascript/runtime/interpreter/interpreter-inl.h"

namespace ark::test {
using ark::ecmascript::EcmaRuntimeCallInfo;
using ark::ecmascript::JSTaggedValue;
using ark::ecmascript::JSThread;

thread_local bool TestHelper::isLeaf_ = true;
// NOLINTNEXTLINE(fuchsia-statically-constructed-objects)
ecmascript::JSHandle<ecmascript::JSFunction> TestHelper::methodFunction_ {};

std::unique_ptr<EcmaRuntimeCallInfo> TestHelper::CreateEcmaRuntimeCallInfo(JSThread *thread, JSTaggedValue newTgt,
                                                                           ArraySizeT argvLength)
{
    auto method = thread->GetEcmaVM()->GetMethodForNativeFunction(nullptr);
    if (isLeaf_ && thread->GetCurrentFrame() != nullptr) {
        method->ExitNativeMethodFrame(thread);
    }
    isLeaf_ = true;

    const uint8_t testDecodedSize = 2;
    // argvLength includes number of int64_t to store value and tag of function, 'this' and call args
    // It doesn't include new.target argument
    uint32_t numActualArgs = argvLength / testDecodedSize + 1;

    std::vector<TaggedValue> args;
    for (size_t i = 0; i < numActualArgs; ++i) {
        args.emplace_back(JSTaggedValue::VALUE_UNDEFINED);
    }

    Frame *frame =
        method->EnterNativeMethodFrame<ark::ecmascript::JSInvokeHelper>(thread, 0, numActualArgs, args.data());

    auto callInfo = std::make_unique<EcmaRuntimeCallInfo>(thread, numActualArgs,
                                                          reinterpret_cast<JSTaggedValue *>(&frame->GetVReg(0)));

    callInfo->SetFunction(methodFunction_.GetTaggedValue());
    callInfo->SetNewTarget(newTgt);
    return callInfo;
}

Frame *TestHelper::SetupFrame(JSThread *thread, [[maybe_unused]] EcmaRuntimeCallInfo *info)
{
    isLeaf_ = false;
    // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
    ASSERT((void *)info->GetArgAddress(0) == &thread->GetCurrentFrame()->GetVReg(0));
    return thread->GetCurrentFrame()->GetPrevFrame();
}

void TestHelper::TearDownFrame([[maybe_unused]] JSThread *thread, [[maybe_unused]] Frame *prev)
{
    isLeaf_ = true;
    auto frame = thread->GetCurrentFrame();
    while (frame != nullptr && frame->GetPrevFrame() != prev) {
        Method::ExitNativeMethodFrame(thread);
        frame = thread->GetCurrentFrame();
    }
}
}  // namespace ark::test
